#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置根节点名字
    ui->treeWidget->setHeaderLabel("动物朋友");
    //新增顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    //每个节点都可以设置多个列，这里设置1列
    item1->setText(0, "雪豹");
    //添加到顶层节点中
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "雪狐");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "雪佛兰");
    ui->treeWidget->addTopLevelItem(item3);

    //添加子节点
    QTreeWidgetItem* item4 = new QTreeWidgetItem();
    item4->setText(0, "芝士雪豹");
    item1->addChild(item4);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertTop_clicked()
{
    //获取输入框内容
    const QString& text = ui->lineEdit->text();
    //构造一个QTreeWidgetItem
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    //添加到顶层节点中
    ui->treeWidget->addTopLevelItem(item);
}



void Widget::on_pushButton_insertItem_clicked()
{
    //获取到当前选中的节点
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem == nullptr)
    {
        return;
    }
    const QString& text = ui->lineEdit->text();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    currentItem->addChild(item);
}

void Widget::on_pushButton_deleteItem_clicked()
{
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem == nullptr)
    {
        return;
    }
    //删除选中元素，需要先获取父元素，通过父元素进行删除
    QTreeWidgetItem* parent = currentItem->parent();
    if(parent == nullptr)
    {
        //顶层元素，
        //先看当前元素是第几个顶层元素的下标
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else//直接通过parent删除子节点
    {
        parent->removeChild(currentItem);
    }
}
